package com.company.nettyT.basic;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class NettyServer {

    public static void main(String[] args) throws Exception {
        //1.创建一个线程组，接受客户端请求
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        //2.创建一个线程组，处理网络io
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        //3.创建服务器端启动助手来配置参数
        ServerBootstrap b = new ServerBootstrap();

        b.group(bossGroup, workerGroup) //设置两个线程组
                .channel(NioServerSocketChannel.class) //使用NioServerSocketChannel作为服务器端通道的实现
                .option(ChannelOption.SO_BACKLOG, 100) //配置线程等待队列的个数
                .childOption(ChannelOption.SO_KEEPALIVE, true)  //保持活动的连接状态
                .childHandler(new ChannelInitializer<SocketChannel>() {//创建一个初始化对象
                    @Override
                    protected void initChannel(SocketChannel sc) throws Exception {
                        sc.pipeline().addLast(new NettyServerHandler());//添加handler到链当中
                    }
                });

        System.out.println("Server is ready.....");

        ChannelFuture cf = b.bind(9999).sync();//绑定端口 bind方法是异步的 sync方法是同步阻塞的



        System.out.println("Server is starting......");

        //关闭通道
        cf.channel().closeFuture().sync();//异步
        //关闭线程池
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();

    }


}
